﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace Chat
{
    public class TcpConnection<InCmd,OutCmd> : Connection<InCmd,OutCmd>
        where InCmd : Command where OutCmd : Command
    {
        private TcpClient Client { get; set; }

        // for use at client side
        public TcpConnection(IPEndPoint ipEndPoint)
        {
            Client = new TcpClient();

            Client.Connect(ipEndPoint);
        }

        // for use at server side
        public TcpConnection(TcpClient client)
        {
            Client = client;
        }

        public override int ReceiveTimeout
        {
            get { return Client.ReceiveTimeout; }
            set { Client.ReceiveTimeout = value; }
        }

        public override void Close()
        {
            Client.Close();
        }

        public override void SendCmd(
            OutCmd command, CmdSerializer<InCmd, OutCmd> serializer)
        {
            serializer.Serialize(Client.GetStream(), command);
        }

        public override InCmd ReceiveCmd(CmdSerializer<InCmd, OutCmd> serializer)
        {
            return serializer.DeserializeCommand(Client.GetStream());
        }
    }
}
